<!-- 商品编辑弹窗 -->
<template>
  <div class="ele-body">
    <a-card :title="commodityModalApp.title" :bordered="false">
      <a-form
        ref="form2"
        :model="commodityModalApp.commodity"
        :rules="commodityModalApp.rules"
        :label-col="{md: {span: 7}, sm: {span: 24}}"
        :wrapper-col="{md: {span: 17}, sm: {span: 24}}">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="编号:" name="codeNum">
              <a-input
                disabled="true"
                v-model:value="commodityModalApp.commodity.codeNum"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="描述信息:" name="description">
              <a-input
                v-model:value="commodityModalApp.commodity.description"
                placeholder="请输入描述信息"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="商品类别:" name="category">
              <m-dict-select
                v-model:value="commodityModalApp.commodity.category"
                placeholder="请选择商品类别"
                dict="商品类别"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="用户:" name="userId">
              <a-input
                v-model:value="commodityModalApp.commodity.userId"
                placeholder="请输入用户"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="店铺:" name="shopId">
              <m-entity-select
                :default-value="commodityModalApp.commodity.shopName"
                v-model:value="commodityModalApp.commodity.shopId"
                placeholder="请选择店铺"
                module="merchant"
                entity="Shop"
                class="ele-fluid"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="附件图片:" name="attachments">
              <MAttachment
                :associateFormId="commodityModalApp.commodity.eid"
                @fileList="handleFile"
                associate-form-name="Commodity"
                operator-type="edit"
                ref="attachment"
              >
              </MAttachment>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
              <!--class="ele-pull-right"-->
              <div v-if="commodityModalApp.display">
                <teleport to="#commodityEditModalFooter">
                  <div>
                    <a-space size="middle">
                      <a-button @click="commodityListApp.editModalShowing=false">取消
                      </a-button>
                      <a-button
                        type="primary"
                        @click="onSubmit(commodityModalApp.commodity)"
                        :loading="loading">提交
                      </a-button>
                      <!--<a-button v-if="!eid"
                                type="dashed"
                                @click="continueSubmit"
                                :loading="loading">继续提交
                      </a-button>-->
                    </a-space>
                  </div>
                </teleport>
              </div>
              <div v-if="!commodityModalApp.display">
                <a-space size="middle">
                  <a-button @click="onBack()">返回列表</a-button>
                  <a-button
                    type="primary"
                    @click="onSubmit(commodityModalApp.commodity)"
                    :loading="loading">提交
                  </a-button>
                  <!--<a-button v-if="!eid"
                            type="dashed"
                            @click="continueSubmit"
                            :loading="loading">继续提交
                  </a-button>-->
                </a-space>
              </div>

            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

  </div>

</template>

<script>
import {defineComponent, inject, reactive, onMounted,ref} from 'vue'
import {useRoute, useRouter} from "vue-router"
import {CommodityService} from "@/views/mall/good/commodity/commodityService";
import {VXETable} from 'vxe-table'
import {useStore} from "vuex";
import regions from 'ele-admin-pro/packages/regions.js';


import MDictSelect from "@/components/MDict/dictSelect";
import MEntitySelect from "@/components/MEntity/entitySelect";
import MAttachment from "@/components/MFileUpload/attachment";
import attachmentService from "@/components/MFileUpload/attachmentService"
export default defineComponent({
  components: {
    MAttachment,
    MDictSelect,
    MEntitySelect,
  },
  setup() {
    // 省市区数据
    const cityData = regions
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    let routeId = route.params.id;
    let commodityListApp = inject('commodityListApp', reactive({}));
    let commodityGrid = inject('commodityGrid', reactive({}))

    const commodityModalApp = reactive({
      id: null,
      commodity: {},
      isEdit: false,
      display: false
    });
    commodityModalApp.rules = {
      description: [
        {
          required: true,
          type: 'string',
          message: '请输入描述信息',
          trigger: 'blur'
        }
      ],
      category: [
        {
          required: false,
          type: 'string',
          message: '请输入商品类别',
          trigger: 'blur'
        }
      ],
      userName: [
        {
          required: false,
          type: 'string',
          message: '请输入用户',
          trigger: 'blur'
        }
      ],
      userId: [
        {
          required: false,
          type: 'string',
          message: '请输入用户',
          trigger: 'blur'
        }
      ],
      shopName: [
        {
          required: false,
          type: 'string',
          message: '请输入店铺',
          trigger: 'blur'
        }
      ],
      shopId: [
        {
          required: true,
          type: 'number',
          message: '请输入店铺',
          trigger: 'blur'
        }
      ],
    }

    onMounted(() => {
      //清理数据
      commodityModalApp.commodity = reactive({});
      if (routeId) {//路由
        commodityModalApp.id = routeId;
        commodityModalApp.display = false;
        findCommodity(commodityModalApp.id);
      } else if (commodityListApp.editModalForEdit) {//修改弹窗
        commodityModalApp.id = commodityListApp.currentId;
        commodityModalApp.display = true;
      } else if (!commodityListApp.editModalForEdit && commodityListApp.addModalForEdit) {//新增弹窗
        CommodityService.getCode().then((res) => {
          commodityModalApp.commodity.codeNum="C"+res.data;
        })
        commodityModalApp.display = true;
      } else {
        // commodityModalApp.title = "新增学生";
      }
      if (commodityModalApp.id) findCommodity(commodityModalApp.id);
    })

    const findCommodity = (id) => {
      CommodityService.findCommodityForView(id).then((res) => {
        commodityModalApp.commodity = res.data;
        //TODO:为编辑准备.
        // commodityModalApp.title = "编辑学生 " + commodityModalApp.commodity.name;
      }).catch(error => {
        VXETable.modal.message({content: `查找学生出错，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:提交 新增&编辑*/
    const onSubmit = (data) => {
      // debugger;
      //当为数组时用逗号连接
      if (data.eid) {
        //修改
        CommodityService.updateCommodity(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          saveFile(res.data.eid,"Commodity")
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      } else {
        //新增
        CommodityService.saveCommodity(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          saveFile(res.data.eid,"Commodity")
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      }
    }

    /*TODO:继续提交*/
    const continueSubmit = () => {
      VXETable.modal.message({content: 'error 提示', status: 'error'});
    }

    /*TODO:返回列表*/
    const onBack = () => {
      router.push(`/mall/good/commodity`);
      store.dispatch('user/tabRemove', route.fullPath);
      setTimeout(() => {
        console.log("commodityGrid",commodityGrid)
        commodityGrid.value.commitProxy("query");
      }, 1500);
      commodityListApp.editModalShowing = false;
    }
    //Todo 提交附件部分功能
    const attachment = ref(null);
    let fileList = reactive([]);
    let operatorType = ref();
    const handleFile=(files)=>{
      fileList.values=files;
    }
    let saveFile = (associateFormId,associateFormName) => {

      if (fileList.values.length !== 0) {
        let formData = new FormData();
        //表单名--对应实体表名
        let formDto = {associateFormId: associateFormId, associateFormName: associateFormName};
        let fileUploadDto = JSON.stringify(formDto)
        formData.append("fileUploadDto", new Blob([fileUploadDto], {type: "application/json"}));
        fileList.values.forEach(file => {
          formData.append('files', file)
        });

        attachmentService.saveFile(formData).then(() => {
          fileList = [];
          VXETable.modal.message({content: '上传成功', status: 'success'});
          //更改上传组件的状态为编辑状态
          operatorType = "edit";
          cleanFileList(associateFormId,associateFormName);
        }).catch((error) => {
          // loading.value = false
          VXETable.modal.message({content: '上传失败' + `系统错误，原因是：${error.message}`, status: 'error'});
        });
      }

    }

    //清空子父组件fileList并刷新子组件reFileList
    let cleanFileList = (associateFormId,associateFormName) => {
      fileList.value = [];
      attachment.value.cleanFileList();
      attachment.value.findFile(associateFormId ,associateFormName);
    }
    return {
      cityData,
      routeId,
      commodityListApp,
      commodityModalApp,
      onSubmit,
      continueSubmit,
      onBack,
      handleFile,
      operatorType,
      attachment
    }

  },
})
</script>

<style scoped>

</style>
